import torch
import torch.optim as optim
import torch.nn.functional as F

from model import Net
from dataset import train_loader


def train(num_epochs):
    network = Net()

    # Defined in file: ./chapter_deep-learning-computation/use-gpu.md
    def try_gpu(i=0):
        """Return gpu(i) if exists, otherwise return cpu()."""
        if torch.cuda.device_count() >= i + 1:
            return torch.device(f'cuda:{i}')
        return torch.device('cpu')

    device = try_gpu()

    network = network.to(device)
    optimizer = optim.SGD(network.parameters(), lr=0.01,
                          momentum=0.5)
    train_losses = []
    train_counter = []

    for epoch in range(num_epochs):
        network.train()
        for batch_idx, (data, target) in enumerate(train_loader):
            X, Y = data.to(device), target.to(device)
            optimizer.zero_grad()
            # output = network(data)
            # loss = F.nll_loss(output, target)
            output = network(X)
            loss = F.nll_loss(output, Y.long())
            loss.backward()
            optimizer.step()
            if batch_idx % 10 == 0:
                print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                    epoch, batch_idx * len(data), len(train_loader.dataset),
                           100. * batch_idx / len(train_loader), loss.item()))
                train_losses.append(loss.item())
                train_counter.append(
                    (batch_idx * 64) + ((epoch - 1) * len(train_loader.dataset)))
                torch.save(network.state_dict(), './model.pth')
                torch.save(optimizer.state_dict(), './optimizer.pth')


if __name__ == '__main__':
    train(10)
